#!/usr/bin/R --vanilla --slave -f
#
# Comparing R json libraries (they suck) vs tnet strings
#
# tnet strings require pgi.array and pgi.object
#
# 153 rows
# 10 iteration = 928 ms, iteration = 93 ms
#
# how the fuck is it taking almost a milliosecond per row?  jesus christ.
#
# RESULTS
#
# - dumping is marginally faster than RJSONIO in the row-order case (93ms vs
# 123 ms)
# - it's much slower in the column order case (25 ms vs 3.6 ms)
# - CSV is 2 ms in this case

source('tnet.R')

compare <- function(lib, data.name, options) {
  # Hacky way of doing "Flags"
  verbose=F
  # pre-allocate
  transpose=T
  time=F
  do.load=F

  eval(parse(text=options))

  if (verbose) {
    cat('LIB', lib, '\n')
    cat('DATA', data.name, '\n')
    cat('OPTIONS', options, '\n')
    cat('---\n')
  }

  if (lib == 'tnet.R') {
    dump <- tnet.dump
  } else if (lib == "csv")  {  # do nothing
    dump <- function(x) { write.csv(x, file="/dev/null") }
  } else {
    require(lib, character.only=TRUE)
    dump <- toJSON
  }

  data(list=data.name)
  if (data.name == 'mtcars') {
    data.set <- mtcars
  } else if (data.name == 'airquality') {
    data.set <- airquality
  } else {
    data.set <- NULL
  }

  # data.set is a data frame, which is serialized to JSON by default in column
  # order.  Tranposing it puts it in row order, like:
  # [ {"a": 1, "b": 2}, {"a":3, "b":4} ] instead of {a: [1 2] b [3 4]}
  if (transpose) {
    rows = list()
    column.names = names(data.set)
    for (i in 1:nrow(data.set)) {
      names(data.set[i,])
      rows[[i]] = data.set[i,]  # row index
    }
    data.set <- rows
  }


  if (do.load) {
    if (time) {
      n <- 10
      cat(paste('\titerations', n, '\n'))
      # binary
      f <- file('../_tmp/airquality.tnet', 'rb')

      # 4/2013: don't think this is working
      d <- readBin(f, "character")
      cat("D", d)

    } else {
      cat(dump(data.set))
    }

  } else {  # dump
    if (time) {
      n <- 10
      cat(paste('\titerations', n))

      t <- system.time(replicate(n, dump(data.set)))
      cat(paste('\t', length(data.set), 'rows\n'))
      cat(paste('\tseconds of user time', t[1], '\n'))
    } else {
      cat(dump(data.set))
    }
  }
}

args <- commandArgs(trailingOnly=TRUE)
action <- args[1]

if (action == 'dump-bench') {
  n <- 133
  table <- cars[rep(1:nrow(cars), each=n),]
  t <- system.time( str <- tnet.dump(table) )
  cat(paste('\tcopies ', n, '\n'))
  cat(paste('\trows', nrow(table), '\n'))
  cat(paste('\toutput size in bytes', nchar(str), '\n'))
  cat(sprintf('\tmilliseconds of user time: %.1f\n', 1000 * t[1]))
  #cat('output:\n')
  #cat(str)
} else {
  lib <- args[1]
  data.name <- args[2]
  options <- args[3]

  compare(lib, data.name, options)
}
